/* debugger_main.c 
**
** Copyright 2006, Brian Swetland.  All rights reserved.
** See provided LICENSE file or http://frotz.net/LICENSE for details.
*/

#include "at91sam7s.h"
#include "devices.h"
#include "usb.h"

void enable_fiq();

void map_sram_to_0(int yes)
{
    vu4 *zero = (vu4*) 0;
    unsigned n;

        /* brilliantly the AT91SAM7 can only *toggle*
           the mapping of sram, so we have to determine
           empirically, what the current state is */
    
    n = *zero;
    *zero = n - 1;
    if(n == *zero) {
            /* flash is at 0 */
        if(!yes) return;
    } else {
            /* ram is at 0 */
        if(yes) return;
    }
    
        /* toggle the mapping state */
    *((vu4*) 0xffffff00) = 1;
    
}

void boot(void)
{
    AT91PIO *pio = AT91PIO_ADDR;
    AT91AIC *aic = AT91AIC_ADDR;
    unsigned n;
    
        /* disable watchdog */
    *((vu4*) 0xfffffd44) = 0x3fff8fff;

    map_sram_to_0(1);
    
        /* disable USB pullup */
    pio->output_enable = (1 << 25);
    pio->data_clear = (1 << 25);

        /* initialize USB device controller */
    usb_init();

        /* wait a moment and enable USB pullup */
    for(n = 0; n < 10000; n++);
    pio->data_set = (1 << 25);

        /* route USB interrupts to FIQ and enable USB interrupts */
    aic->FFER = (1 << PID_UDP);
    aic->IECR = (1 << PID_UDP);
    enable_fiq();

    jtag_init();
    
    for(;;);
}
